import fs, {PathLike} from 'node:fs';
import path from 'node:path';

class FileUtil {

    /**
     * 读取文件
     * @param {fs.PathOrFileDescriptor} path 路径
     */
    read(path: fs.PathOrFileDescriptor) {
        return fs.readFileSync(path, "utf-8")
    }

    /**
     * 获取文件夹下的所有文件
     * @param {string} directory 文件夹
     * @return {Promise<string[]>}
     */
    getAllFileInDirectory(directory: string): Promise<string[]> {
        return new Promise((resolve, reject) => {
            fs.readdir(directory, async (error, files) => {
                if (error) {
                    return reject(error);
                }
                let resArr: string[] = [];
                // 获取完整路径
                const fullPathFiles: string[] = files.map(file => path.join(directory, file));
                for (let fullPathFile of fullPathFiles) {
                    if (fs.statSync(fullPathFile).isDirectory()) {
                        const res = await this.getAllFileInDirectory(fullPathFile);
                        if (res) {
                            resArr = resArr.concat(res);
                        }
                    } else {
                        resArr.push(fullPathFile);
                    }
                }
                resolve(resArr);
            });
        });
    }

    /**
     * 确保目录存在，没有则创建
     * @param {PathLike} path 路径
     */
    ensureDirectoryExists(path: PathLike) {
        return new Promise((resolve, reject) => {
            fs.access(path, fs.constants.F_OK, err => {
                if (err) {
                    if (err.code === 'ENOENT') {
                        fs.mkdir(path, {recursive: true}, (err1, path1) => {
                            if (err1) {
                                reject(err1);
                            } else {
                                resolve(path1);
                            }
                        })
                    } else {
                        reject(err);
                    }
                } else {
                    resolve(true)
                }
            })
        })
    }

    /**
     * 保存文件
     * @param {string | NodeJS.ArrayBufferView} content 文件内容
     * @param {string} filePath 文件路径
     * @param {boolean} [autoCreateDirectory=true] 自动创建目录
     */
    async saveFile(content: string | NodeJS.ArrayBufferView, filePath: string, autoCreateDirectory: boolean = true) {
        if (autoCreateDirectory) {
            const dirPath = path.dirname(filePath);
            await this.ensureDirectoryExists(dirPath)
        }
        fs.writeFileSync(filePath, content, {
            encoding: 'utf-8'
        });
    }
}

export default new FileUtil()
